using System.Collections;
using System.Threading;
using Microsoft.SPOT;

namespace CodeConsult.Nordic.nRF8001.ApplicationControlInterface
{
    public class AciQueue : Queue
    {
        private readonly ManualResetEvent _queueFullResetEvent = new ManualResetEvent(false);
        private readonly object _queueLock = new object();

        public int MaxSize { get; set; }

        public AciQueue(int maxSize)
        {
            MaxSize = maxSize;
        }

        public override void Enqueue(object obj)
        {
            if (Count == MaxSize)
            {
                Debug.Print("Queue full, waiting ...");
                _queueFullResetEvent.WaitOne(-1, false);
                Debug.Print("Queue full, waiting done");
            }

            lock (_queueLock)
            {
                base.Enqueue(obj);
                if (Count == MaxSize)
                {
                    _queueFullResetEvent.Reset();
                }
            }
        }

        public override object Dequeue()
        {
            lock (_queueLock)
            {
                var res = base.Dequeue();
                _queueFullResetEvent.Set();
                return res;
            }
        }
    }
}
